package com.study.juc.secstudy;

import org.junit.internal.runners.statements.RunAfters;

import java.util.concurrent.TimeUnit;

public class BooleanLock implements Lock{

    private boolean lock =false;
    private Thread holder;
    @Override
    public void lock() throws InterruptedException {
        synchronized (this){
            while(lock){
                if(holder == Thread.currentThread())break;
                this.wait();
            }
            lock = true;
            holder = Thread.currentThread();
        }
    }

    @Override
    public void unlock() {
        synchronized (this){
            if(holder == Thread.currentThread()){
                lock = false;
                holder = null;
                this.notifyAll();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {

        BooleanLock booleanLock = new BooleanLock();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName()+"no enter");
                    booleanLock.lock();
                    System.out.println(Thread.currentThread().getName()+"enter");
                    if(Thread.currentThread().getName().equals("T1")){
                        TimeUnit.HOURS.sleep(1L);
                    }else{
                        TimeUnit.SECONDS.sleep(1L);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    booleanLock.unlock();
                }

            }
        };
        Thread thread = new Thread(runnable,"T1");
        Thread thread2 = new Thread(runnable,"T2");

        thread.start();
        TimeUnit.SECONDS.sleep(3L);

        thread2.start();
        TimeUnit.SECONDS.sleep(10L);
        System.out.println("开始打断t1");

        thread.interrupt();


    }
}
